<?php

namespace app\api\model;

use app\admin\model\CompanySpecModel;
use app\admin\model\VipCard;
use think\Model;
use think\model\concern\SoftDelete;
use think\cache\driver\Redis;

class CompanyPackageModel extends ApiModel
{

    use SoftDelete;


    protected $expire_time = 7*24*60*60;
    // 表名
    protected $name = 'company_package';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    // 追加属性
    protected $append = [

    ];


    public function cate()
    {
        return $this->belongsTo(CompanyCateModel::class, 'company_cate_id', 'id', [], 'LEFT');
    }

    public function getCompanyPackage($params)
    {
        $area_name = $params['area_name'] ?? '';

        $uid =  $params['uid'] ?? 0;
        $vipDiscount = 0;
        $user = (new MemberModel())->where(['id' => $uid])->find();
        if($user && $user['vip_type'] > 0){
            $vipDiscount = (new VipCard())->where(['id' => $user['vip_type']])->value('discount');
        }

        $redis = new Redis(config('cache.redis'));
        $key = $area_name.'_company_package_'.$vipDiscount;
        $companyCate = $redis->get($key);
        $companyCate = [];
        if(!$companyCate){
            //获取分类
            $companyCate = (new CompanyCateModel)
                ->where(['status' => 1])
                ->order('sort desc')
                ->field('id,name')
                ->select();
            foreach ($companyCate as &$cate) {
                //获取套餐
                $companyPackage = self::where(['company_cate_id' => $cate['id'], 'status' => 1])
                    ->field('id,name,type_name,company_cate_id,spec,image,unit,content')
                    ->order('sort desc')
                    ->select()->toArray();
                if ($companyPackage) {
                    foreach ($companyPackage as &$package) {
                        $package['cate_name'] = $cate['name'];
                        $package['image'] = config('app.image_url') . $package['image'];

                        $spec = json_decode($package['spec'], true);
                        $package['spec'] = $this->packageSpc($spec, $package['id'], $area_name,$vipDiscount);
                        $minPrice = min(array_column( $package['spec'], 'price'));
                        $minIndex = array_search($minPrice, array_column($package['spec'], 'price'));
                        if ($minIndex === false) {
                            unset($package['spec']);
                            continue;
                        }
                        $minItem = $package['spec'][$minIndex];
                        $package['price'] = $minItem['price'] . "/" . $minItem['name'];

                        $content = json_decode($package['content'], true);
                        $package['content'] = array_map(function($key, $value) {
                            return array('key' => $key, 'value' => $value);
                        }, array_keys($content), $content);
                        $package['content_nums'] = count($package['content']) . "项服务内容";
                    }
                }

                $cate['children'] = $companyPackage;
            }
//            $redis->set($key,$companyCate,$this->expire_time);
        }


        return $this->api_success('获取成功', $companyCate);

    }


    public function packageSpc($spec, $package_id, $area_name,$vipDiscount)
    {
        //查询是否在多地区规格
        foreach ($spec as $key => &$value) {
            $area_spec = (new CompanyPriceModel())
                ->where(['company_package_id' => $package_id,'spec_id'=>$value['spec_id']])
                ->find();
            if($area_spec){
                $area = explode(',',$area_spec['area_ids']);
                if(in_array($area_name,$area)){
                    $value['price'] = $area_spec['price'];
                }
            }
        }


        //查询规格名称
        $company_spec = (new CompanySpecModel())->column('name','id');
        foreach ($spec as $key=>&$value){
            $value['name'] = $company_spec[$value['spec_id']] ?? '';
            if(!$value['name']){
                unset($spec[$key]);
            }
            $value['vip_price'] = '';
            if($vipDiscount){
                $value['vip_price'] = number_format($value['price'] * $vipDiscount / 10,2) . "";
            }

        }

        return $spec;
    }


}
